﻿using System;
using System.Drawing;
using System.Windows.Forms;
using ZXing;
using ZXing.QrCode;

namespace LikeProxy.Controls
{
    public partial class QrcodeControl : UserControl
    {
        public QrcodeControl()
        {
            InitializeComponent();
            pictureBox_qrcode.Image = TextToQrcode(textBox_content.Text);
        }

        private void button_Click(object sender, EventArgs e)
        {

            Button btn = sender as Button;
            if (btn.Name == "button_qrcode_encode")
            {
                if (string.IsNullOrEmpty(textBox_content.Text))
                {
                    MessageBox.Show("文本不能为空！", "提示");
                    return;
                }
                pictureBox_qrcode.Image = TextToQrcode(textBox_content.Text);
            }
            else if (btn.Name == "button_qrcode_decode")
            {
                OpenFileDialog fileDialog = new OpenFileDialog
                {
                    Filter = "图像文件(*.jpg;*.jpg;*.jpeg;*.gif;*.png)|*.jpg;*.jpeg;*.gif;*.png",
                    ValidateNames = true,
                    CheckPathExists = true,
                    CheckFileExists = true
                };
                if (fileDialog.ShowDialog() == DialogResult.OK)
                {
                    pictureBox_qrcode.Image = Image.FromFile(fileDialog.FileName);
                    textBox_content.Text = QrcodeToString(pictureBox_qrcode.Image as Bitmap);
                }


            }




        }

        Bitmap TextToQrcode(string text)
        {
            BarcodeWriter writer = new BarcodeWriter
            {
                Format = BarcodeFormat.QR_CODE
            };
            writer.Options = new QrCodeEncodingOptions
            {
                DisableECI = true,
                //设置内容编码
                CharacterSet = "UTF-8",
                //设置二维码的宽度和高度
                Width = 300,
                Height = 300,
                //设置二维码的边距,单位不是固定像素
                Margin = 1
            };
            return writer.Write(textBox_content.Text);
        }

        string QrcodeToString(Bitmap image)
        {
            BarcodeReader reader = new BarcodeReader();
            reader.Options.CharacterSet = "UTF-8";
            Result result = reader.Decode(image);
            return result == null ? "" : result.Text;
        }

        private void pictureBox_qrcode_Click(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }

        private void textBox_content_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
